import { Form } from 'antd';
import { FunctionComponent } from 'react';
import { widgets } from './widgets/widgets';
import { FormProperty } from '@/pages/form-model/model/formProperty';
import ObjectWidget from './widgets/object/object.widget';
import useObservableState from '@/pages/form-model/observeState';
import { ObjectProperty } from './model/object.property';

interface WidgetCellProps {
  formProperty: FormProperty;
}

export default function SFormItem(widgetCellProps: WidgetCellProps) {
  const { formProperty } = widgetCellProps;
  const {
    $props,
    $formItemProps,
    $valueChange,
    render,
    widget = 'input',
    type,
    namePath,
  } = formProperty;
  const Com: FunctionComponent<any> = render || widgets[widget];
  const [comProps] = useObservableState($props);
  const [itemProps] = useObservableState($formItemProps);

  function handleChange(value: any) {
    $valueChange.next(value);
  }

  if (!Com) {
    return <>控件不存在</>;
  }

  if (type === 'object') {
    return <ObjectWidget formProperty={formProperty as ObjectProperty} />;
  }

  return (
    <Form.Item {...itemProps} name={namePath}>
      <Com {...comProps} onChange={handleChange} />
    </Form.Item>
  );
}
